package com.kingyea.gradle.task;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.commons.io.IOUtils;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;

import com.kingyea.esb.commons.datawrap.MessageData;
import com.kingyea.gradle.extension.WebServiceServer;
import com.kingyea.gradle.jmx.JMXClientHelper;

public class WebServiceDeployTask extends DefaultTask {
	
	private static final String METHOD_DEPLOY_WEB_SERVICE_BUNDLE = "deployWebServiceBundle";


	@TaskAction
	public void deployWebService() throws Exception {
		WebServiceServer server = this.getProject().getExtensions().getByType(WebServiceServer.class);
		server.getJmxServiceUrl();
		Map<String, Object> environment = new HashMap<>();
	    String[] credentials = { server.getUserName(), server.getPassword() };
	    environment.put("jmx.remote.credentials", credentials);
	    JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(server.getJmxServiceUrl()), environment);
		Object result = JMXClientHelper.invokeRemoteMethod(connector.getMBeanServerConnection(), 
				server.getObjectName(), METHOD_DEPLOY_WEB_SERVICE_BUNDLE, 
				new Object[]{getBundleData()}, new String[]{byte[].class.getName()});
		MessageData data = (MessageData) result;
		System.out.println((data.isSuccess() ? "发布成功, " : "失败失败, ") + data.getMessage());
	}
	
	
	private byte[] getBundleData() throws FileNotFoundException, IOException {
		String destPath = this.getProject().getBuildDir().getAbsolutePath() + "/libs/" + this.getProject().getName() + "-" + this.getProject().getVersion() + ".jar";
		System.out.println(destPath);
		try(FileInputStream fis = new FileInputStream(destPath);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
			IOUtils.copy(fis, baos);
			return baos.toByteArray();
		}
	}
}
